<template>
  <view class="search-container">
    <view class="search-box" :class="{ 'search-box-active': isActive }">
      <!-- 搜索图标 -->
      <image class="search-icon" :src="searchIcon" mode="aspectFit" />

      <!-- 输入框 -->
      <input
        class="search-input"
        type="text"
        :value="keyword"
        placeholder="请输入搜索内容"
        placeholder-class="placeholder-style"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
      />

      <!-- 清除按钮 -->
      <image
        v-if="showClear && keyword"
        class="clear-icon"
        :src="clearIcon"
        mode="aspectFit"
        @tap.stop="handleClear"
      />
    </view>

    <nut-button class="search-btn" @tap="handleSearch" type="primary">搜索</nut-button>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import searchIcon from "@/assets/icon/search.svg";
import clearIcon from "@/assets/icon/close.svg";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue", "search"]);

const isActive = ref(false);
const keyword = ref(props.modelValue || "");

// 计算是否显示清除按钮
const showClear = computed(() => {
  return keyword.value.length > 0;
});

// 输入处理
const handleInput = (event: any) => {
  keyword.value = event.detail.value;
  emit("update:modelValue", keyword.value);
};

// 获取焦点
const handleFocus = () => {
  isActive.value = true;
};

// 失去焦点
const handleBlur = () => {
  isActive.value = false;
};

// 清除输入
const handleClear = () => {
    console.log('clear');
  keyword.value = "";
  emit("update:modelValue", "");
};

// 搜索
const handleSearch = () => {
  emit("search", keyword.value);
};
</script>

<style lang="scss">
.search-container {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  gap: 20rpx;

  .search-box {
    flex: 1;
    display: flex;
    align-items: center;
    height: 70rpx;
    background-color: #f5f5f5;
    border-radius: 35rpx;
    padding: 0 20rpx;
    // transition: all 0.3s ease;
    border: 1rpx solid #f0f0f0;

    &-active {
      background-color: #ffffff;
      border: 1rpx solid #d0d0d0;
    }

    .search-icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 10rpx;
    }

    .search-input {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
      color: #333333;
      padding: 0 10rpx;
    }

    .clear-icon {
      width: 32rpx;
      height: 32rpx;
      margin-left: 10rpx;
    }

    .placeholder-style {
      color: #999999;
      font-size: 28rpx;
    }
  }

  // .search-btn{
  //   width: 120rpx;
  //   height: 70rpx;
  //   line-height: 70rpx;
  //   background-color: #f2270c;
  //   color: #ffffff;
  //   font-size: 28rpx;
  //   border-radius: 35rpx;
  // }
}
</style>
